<template>
  <div class="community-page">
    <van-nav-bar title="社区" right-text="发表" @click-right="showPublish" />
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh">
      <van-list
        v-model:loading="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <div class="feed-list">
          <div v-for="(item, index) in list" :key="index" class="feed-item">
            <div class="feed-header">
              <img :src="item.avatar" alt="头像" class="avatar" />
              <div class="user-info">
                <div class="nickname">{{ item.nickname }}</div>
                <div class="time">{{ formatTime(item.createTime) }}</div>
              </div>
            </div>
            <div class="feed-content">
              <p>{{ item.text }}</p>
              <div class="images" v-if="item.images && item.images.length">
                <div class="image-grid" :class="`grid-${Math.min(item.images.length, 3)}`">
                  <img
                    v-for="(img, idx) in item.images"
                    :key="idx"
                    :src="img"
                    alt="图片"
                    class="feed-image"
                    @click="previewImage(item.images, idx)"
                  />
                </div>
              </div>
            </div>
            <div class="feed-footer">
              <van-button
                type="primary"
                plain
                hairline
                size="small"
                :icon="item.liked ? 'like' : 'like-o'"
                :class="{ 'liked': item.liked }"
                @click="toggleLike(item)"
              >
                {{ item.likes }}
              </van-button>
              <van-button
                type="info"
                plain
                hairline
                size="small"
                icon="comment-o"
                @click="showComment(item)"
              >
                {{ item.comments }}
              </van-button>
              <van-button
                type="warning"
                plain
                hairline
                size="small"
                icon="share-o"
                @click="showShareOptions(item)"
              >
                分享
              </van-button>
            </div>
            <div class="comments-section" v-show="item.showComments">
              <van-field
                v-model="item.newComment"
                rows="1"
                autosize
                type="textarea"
                placeholder="留下你的评论..."
              >
                <template #button>
                  <van-button size="small" type="primary" @click="addComment(item)">发送</van-button>
                </template>
              </van-field>
              <div class="comments-list">
                <div
                  v-for="(comment, cidx) in item.commentsList"
                  :key="cidx"
                  class="comment-item"
                >
                  <img :src="comment.avatar" alt="头像" class="comment-avatar" />
                  <div class="comment-content">
                    <div class="comment-user">{{ comment.user }}</div>
                    <div class="comment-text">{{ comment.text }}</div>
                    <div class="comment-footer">
                      <span class="comment-time">{{ formatTime(comment.time) }}</span>
                      <van-button
                        size="mini"
                        plain
                        :icon="comment.liked ? 'like' : 'like-o'"
                        @click="toggleCommentLike(item, comment)"
                      >
                        {{ comment.likes || '点赞' }}
                      </van-button>
                      <van-button
                        size="mini"
                        plain
                        icon="comment-o"
                        @click="replyComment(item, comment)"
                      >
                        回复
                      </van-button>
                    </div>
                  </div>
                </div>
                <van-empty v-if="!item.commentsList.length" description="暂无评论" />
                <div v-if="item.commentLoading" class="comments-loading">
                  <van-loading type="spinner" size="24px" />
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-list>
    </van-pull-refresh>

    <!-- 发布动态弹窗 -->
    <van-popup
      v-model:show="publishing"
      position="bottom"
      :style="{ height: '80%' }"
      round
    >
      <div class="publish-container">
        <van-nav-bar
          title="发布动态"
          left-text="取消"
          right-text="发布"
          @click-left="cancelPublish"
          @click-right="publishPost"
        />
        <div class="publish-content">
          <van-field
            v-model="newPost.text"
            rows="5"
            autosize
            type="textarea"
            placeholder="这一刻的想法..."
            class="publish-textarea"
          />
          <van-uploader
            v-model="newPost.images"
            multiple
            :max-count="9"
            :after-read="afterReadImage"
            class="publish-uploader"
          />
        </div>
      </div>
    </van-popup>

    <!-- 分享选项弹窗 -->
    <van-action-sheet
      v-model:show="shareVisible"
      title="分享到"
      cancel-text="取消"
    >
      <div class="share-options">
        <div class="share-option" @click="shareToWeChat">
          <van-icon name="wechat" size="24" color="#07C160" />
          <span>微信</span>
        </div>
        <div class="share-option" @click="shareToFriends">
          <van-icon name="friends-o" size="24" color="#FFC300" />
          <span>朋友圈</span>
        </div>
        <div class="share-option" @click="shareToQQ">
          <van-icon name="chat-o" size="24" color="#12B7F5" />
          <span>QQ</span>
        </div>
        <div class="share-option" @click="copyLink">
          <van-icon name="link" size="24" color="#2196F3" />
          <span>复制链接</span>
        </div>
      </div>
    </van-action-sheet>

    <!-- 图片预览 -->
    <van-image-preview v-model:show="showImagePreview" :images="previewImages" :start-position="previewStartPosition" />
  </div>
</template>

<script setup>
import { ref, onMounted, reactive } from "vue";
import {
  showSuccessToast,
  showFailToast,
  showLoadingToast,
  showDialog,
  ImagePreview,
  ActionSheet,
  Empty,
  NavBar,
  List
} from "vant";
import {
  getDynamicList,
  addDynamic,
  addComment as addCommentApi,
  getCommentList,
  likeAction,
  isLiked
} from "../services/community";
import { getCurrentUser, imageUpload } from "../services/user";
import { formatDistanceToNow } from "date-fns";
import { zhCN } from "date-fns/locale";

const list = ref([]);
const currentUser = ref(null);
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const publishing = ref(false);
const shareVisible = ref(false);
const currentShareItem = ref(null);
const showImagePreview = ref(false);
const previewImages = ref([]);
const previewStartPosition = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

const newPost = ref({
  text: "",
  images: [],
});

onMounted(async () => {
  try {
    const userInfo = await getCurrentUser();
    currentUser.value = userInfo;
  } catch (error) {
    showFailToast("获取用户信息失败");
  }
});

const formatTime = (timestamp) => {
  if (!timestamp) return '';
  try {
    return formatDistanceToNow(new Date(timestamp), {
      addSuffix: true,
      locale: zhCN
    });
  } catch (error) {
    return timestamp;
  }
};

const onLoad = async () => {
  if (refreshing.value) {
    list.value = [];
    refreshing.value = false;
    currentPage.value = 1;
    finished.value = false;
  }
  
  await loadDynamics();
  currentPage.value += 1;
};

const loadDynamics = async () => {
  if (refreshing.value) return;
  loading.value = true;
  
  try {
    const res = await getDynamicList({
      current: currentPage.value,
      pageSize: pageSize.value
    });
    
    if (res?.code === 0) {
      const newItems = await Promise.all(res.data.records.map(async (item) => {
        const likedRes = await isLiked({
          dynamicId: item.id,
          type: 0
        });
        
        return {
          id: item.id,
          avatar: item.user.avatarUrl || require('@/assets/default-avatar.png'),
          nickname: item.user.username,
          text: item.content,
          images: item.images || [],
          liked: likedRes?.data || false,
          likes: item.likeCount || 0,
          comments: item.commentCount || 0,
          createTime: item.createTime,
          showComments: false,
          commentsList: [],
          commentLoading: false,
          newComment: "",
        };
      }));
      
      list.value = [...list.value, ...newItems];
      
      if (res.data.records.length < pageSize.value) {
        finished.value = true;
      }
    } else {
      showFailToast(res?.message || "获取动态列表失败");
    }
  } catch (error) {
    console.error("获取动态列表失败:", error);
    handleApiError(error, "获取动态列表失败");
  } finally {
    loading.value = false;
  }
};

const onRefresh = async () => {
  refreshing.value = true;
  finished.value = false;
  currentPage.value = 1;
  await onLoad();
  showSuccessToast("刷新成功");
};

const toggleLike = async (item) => {
  try {
    const res = await likeAction({
      dynamicId: item.id,
      type: 0
    });
    
    if (res?.code === 0) {
      item.liked = !item.liked;
      item.likes += item.liked ? 1 : -1;
      showSuccessToast(item.liked ? "点赞成功" : "取消点赞成功");
    }
  } catch (error) {
    handleApiError(error, "点赞操作失败");
  }
};

const toggleCommentLike = async (item, comment) => {
  try {
    const res = await likeAction({
      commentId: comment.id,
      type: 1
    });
    
    if (res?.code === 0) {
      comment.liked = !comment.liked;
      comment.likes = comment.likes || 0;
      comment.likes += comment.liked ? 1 : -1;
      showSuccessToast(comment.liked ? "点赞成功" : "取消点赞成功");
    }
  } catch (error) {
    handleApiError(error, "点赞操作失败");
  }
};

const showComment = async (item) => {
  item.showComments = !item.showComments;
  
  if (item.showComments && item.commentsList.length === 0) {
    item.commentLoading = true;
    try {
      const res = await getCommentList(item.id);
      if (res?.code === 0) {
        item.commentsList = await Promise.all(res.data.records.map(async (comment) => {
          const likedRes = await isLiked({
            commentId: comment.id,
            type: 1
          });
          
          return {
            id: comment.id,
            user: comment.user.username,
            avatar: comment.user.avatarUrl || require('@/assets/default-avatar.png'),
            text: comment.content,
            time: comment.createdAt,
            liked: likedRes?.data || false,
            likes: comment.likeCount || 0
          };
        }));
      }
    } catch (error) {
      handleApiError(error, "获取评论失败");
    } finally {
      item.commentLoading = false;
    }
  }
};

const replyComment = (item, comment) => {
  item.newComment = `回复 @${comment.user}: `;
};

const addComment = async (item) => {
  if (!item.newComment.trim()) {
    showFailToast("评论内容不能为空");
    return;
  }
  
  try {
    // 检查是否是回复其他评论
    let parentId = null;
    let content = item.newComment;
    const replyMatch = content.match(/^回复\s*@([^:]+):\s*(.*)/);
    
    if (replyMatch) {
      const targetUsername = replyMatch[1];
      content = replyMatch[2];
      
      // 查找原评论的ID
      const targetComment = item.commentsList.find(c => c.user === targetUsername);
      if (targetComment) {
        parentId = targetComment.id;
      }
    }
    
    const res = await addCommentApi({
      dynamicId: item.id,
      content: content,
      parentId: parentId
    });
    
    if (res?.code === 0) {
      // 添加新评论到列表
      item.commentsList.unshift({
        id: res.data,
        user: currentUser.value.username,
        avatar: currentUser.value.avatarUrl || require('@/assets/default-avatar.png'),
        text: content,
        time: new Date().toISOString(),
        liked: false,
        likes: 0
      });
      
      item.comments += 1;
      item.newComment = "";
      showSuccessToast("评论成功");
    }
  } catch (error) {
    handleApiError(error, "评论失败");
  }
};

const showPublish = () => {
  publishing.value = true;
};

const cancelPublish = () => {
  showDialog({
    title: '取消发布',
    message: '确定要放弃编辑的内容吗？',
    showCancelButton: true,
  }).then(() => {
    newPost.value.text = "";
    newPost.value.images = [];
    publishing.value = false;
  }).catch(() => {
    // 用户取消
  });
};

const afterReadImage = (file) => {
  if (file.size > 10 * 1024 * 1024) {
    showFailToast('图片大小不能超过10MB');
    return;
  }
};

const publishPost = async () => {
  if (!newPost.value.text.trim() && !newPost.value.images.length) {
    showFailToast("内容不能为空");
    return;
  }
  
  const loading = showLoadingToast({
    message: "发布中...",
    forbidClick: true,
  });
  
  try {
    const imageUrls = await Promise.all(
      newPost.value.images.map(async (file) => {
        const formData = new FormData();
        formData.append("file", file.file);
        const res = await imageUpload(formData);
        return res.data.url;
      })
    );

    const res = await addDynamic({
      content: newPost.value.text,
      images: imageUrls
    });

    if (res?.code === 0) {
      refreshing.value = true;
      await onLoad();
      newPost.value.text = "";
      newPost.value.images = [];
      publishing.value = false;
      showSuccessToast("发布成功");
    }
  } catch (error) {
    handleApiError(error, "发布失败");
  } finally {
    loading.close();
  }
};

const showShareOptions = (item) => {
  currentShareItem.value = item;
  shareVisible.value = true;
};

const shareToWeChat = () => {
  // 实现微信分享
  showSuccessToast("微信分享功能开发中");
  shareVisible.value = false;
};

const shareToFriends = () => {
  // 实现朋友圈分享
  showSuccessToast("朋友圈分享功能开发中");
  shareVisible.value = false;
};

const shareToQQ = () => {
  // 实现QQ分享
  showSuccessToast("QQ分享功能开发中");
  shareVisible.value = false;
};

const copyLink = () => {
  // 实现复制链接
  const url = `${window.location.origin}/dynamic/${currentShareItem.value.id}`;
  navigator.clipboard.writeText(url)
    .then(() => {
      showSuccessToast("链接已复制");
    })
    .catch(() => {
      showFailToast("复制失败");
    });
  shareVisible.value = false;
};

const previewImage = (images, index) => {
  previewImages.value = images;
  previewStartPosition.value = index;
  showImagePreview.value = true;
};

const handleApiError = (error, defaultMessage) => {
  if (error.response) {
    showFailToast(error.response.data?.message || defaultMessage);
  } else if (error.request) {
    showFailToast("网络连接失败，请检查网络设置");
  } else {
    showFailToast("服务器异常，请稍后再试");
  }
};
</script>

<style scoped>
.community-page {
  background-color: #f7f8fa;
  min-height: 100vh;
}

.feed-list {
  padding: 12px;
}

.feed-item {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-bottom: 16px;
  overflow: hidden;
  padding: 16px;
}

.feed-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 12px;
  background-color: #f0f0f0;
}

.user-info {
  flex: 1;
}

.nickname {
  font-size: 16px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.time {
  font-size: 12px;
  color: #969799;
}

.feed-content {
  margin-bottom: 16px;
}

.feed-content p {
  font-size: 15px;
  line-height: 1.5;
  color: #323233;
  margin: 0 0 12px;
  word-break: break-word;
}

.images {
  margin-top: 12px;
}

.image-grid {
  display: grid;
  grid-gap: 6px;
}

.grid-1 {
  grid-template-columns: 1fr;
}

.grid-2 {
  grid-template-columns: 1fr 1fr;
}

.grid-3, .grid-4, .grid-5, .grid-6, .grid-7, .grid-8, .grid-9 {
  grid-template-columns: 1fr 1fr 1fr;
}

.feed-image {
  width: 100%;
  border-radius: 4px;
  background-color: #f7f8fa;
  object-fit: cover;
  aspect-ratio: 1/1;
}

.feed-footer {
  display: flex;
  align-items: center;
  justify-content: space-around;
  border-top: 1px solid #f2f3f5;
  padding-top: 12px;
  margin-top: 12px;
}

.feed-footer .van-button {
  margin: 0 8px;
  height: 36px;
  flex: 1;
}

.feed-footer .liked {
  color: #ee0a24;
}

.comments-section {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f2f3f5;
}

.comments-list {
  margin-top: 12px;
}

.comment-item {
  display: flex;
  margin-bottom: 12px;
  padding: 8px;
  background-color: #f7f8fa;
  border-radius: 4px;
}

.comment-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
  background-color: #f0f0f0;
}

.comment-content {
  flex: 1;
}

.comment-user {
  font-size: 14px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.comment-text {
  font-size: 14px;
  color: #323233;
  line-height: 1.4;
  margin-bottom: 6px;
  word-break: break-word;
}

.comment-footer {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 10px;
}

.comment-time {
  font-size: 12px;
  color: #969799;
}

.comment-footer .van-button {
  padding: 0 8px;
  height: 24px;
  margin-left: 8px;
}

.comments-loading {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

/* 发布动态弹窗样式 */
.publish-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.publish-content {
  flex: 1;
  padding: 16px;
  overflow-y: auto;
}

.publish-textarea {
  margin-bottom: 16px;
}

.publish-uploader {
  margin-bottom: 16px;
}

/* 分享选项样式 */
.share-options {
  display: flex;
  flex-wrap: wrap;
  padding: 16px;
}

.share-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 25%;
  padding: 16px 8px;
}

.share-option span {
  margin-top: 8px;
  font-size: 12px;
  color: #323233;
}
</style>
